#!/bin/sh

WORK="$PWD/mirror-url-credentials-work.$$"
ORIG_NVM_DIR="${NVM_DIR-}"

cleanup() {
  unset -f nvm_download nvm_get_checksum nvm_compare_checksum
  unset NVM_NODEJS_ORG_MIRROR NVM_IOJS_ORG_MIRROR
  NVM_DIR="${ORIG_NVM_DIR}"
  rm -rf "${WORK}"
}
die () { echo "$@" ; cleanup ; exit 1; }

# args: description, output
assert_masked() {
  case "${2}" in
    *s3cr3t* | *ci-bot*) die "${1} printed the mirror URL credentials; got >${2}<" ;;
  esac
  case "${2}" in
    *'://***@mirror.example.com/dist'*) ;;
    *) die "${1} did not print the masked mirror URL; got >${2}<" ;;
  esac
}

\. ../../../nvm.sh

mkdir -p "${WORK}"

NVM_NODEJS_ORG_MIRROR='https://ci-bot:s3cr3t@mirror.example.com/dist'
NVM_IOJS_ORG_MIRROR='https://ci-bot:s3cr3t@mirror.example.com/dist'
export NVM_NODEJS_ORG_MIRROR NVM_IOJS_ORG_MIRROR

assert_masked 'nvm debug' "$(nvm debug 2>&1)"

NVM_DIR="${WORK}"
nvm_get_checksum() { nvm_echo 'fake_checksum'; }
nvm_compare_checksum() { return 0; }

# nvm_download still receives the unmasked URL
nvm_download() {
  case "$*" in
    *"${NVM_NODEJS_ORG_MIRROR}/v20.0.0/"*) ;;
    *) nvm_err 'nvm_download did not receive the mirror URL credentials' ;;
  esac
  return "${DOWNLOAD_EXIT_CODE-0}"
}
OUTPUT="$(nvm_download_artifact node source std v20.0.0 2>&1)"
assert_masked 'nvm_download_artifact' "${OUTPUT}"
case "${OUTPUT}" in
  *'did not receive'*) die "${OUTPUT}" ;;
esac

OUTPUT="$(DOWNLOAD_EXIT_CODE=1 nvm_download_artifact node source std v20.0.0 2>&1)"
case "${OUTPUT}" in
  *'download from '*' failed'*) ;;
  *) die "expected a download failure message; got >${OUTPUT}<" ;;
esac
assert_masked 'nvm_download_artifact, on a failed download,' "${OUTPUT#*...}"

nvm_download() {
  while [ "$#" -gt 0 ]; do
    if [ "$1" = '-o' ]; then
      nvm_echo '404 Not Found' > "$2"
      return 0
    fi
    shift
  done
}
OUTPUT="$(nvm_download_artifact node source std v20.0.0 2>&1)"
case "${OUTPUT}" in
  *'HTTP 404 at URL '*) ;;
  *) die "expected an HTTP 404 message; got >${OUTPUT}<" ;;
esac
assert_masked 'nvm_download_artifact, on a 404,' "${OUTPUT#*...}"

cleanup
